{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "os.environ['CUDA_VISIBLE_DEVICES'] = '2'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import tensorflow as tf\n",
    "import json"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "with open('dataset-bpe.json') as fopen:\n",
    "    data = json.load(fopen)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "train_X = data['train_X']\n",
    "train_Y = data['train_Y']\n",
    "test_X = data['test_X']\n",
    "test_Y = data['test_Y']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "EOS = 2\n",
    "GO = 1\n",
    "vocab_size = 32000"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "train_Y = [i + [2] for i in train_Y]\n",
    "test_Y = [i + [2] for i in test_Y]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "from tensor2tensor.utils import beam_search\n",
    "\n",
    "def pad_second_dim(x, desired_size):\n",
    "    padding = tf.tile([[[0.0]]], tf.stack([tf.shape(x)[0], desired_size - tf.shape(x)[1], tf.shape(x)[2]], 0))\n",
    "    return tf.concat([x, padding], 1)\n",
    "\n",
    "class Translator:\n",
    "    def __init__(self, size_layer, num_layers, embedded_size, learning_rate):\n",
    "        \n",
    "        def cells(reuse=False):\n",
    "            return tf.nn.rnn_cell.BasicRNNCell(size_layer,reuse=reuse)\n",
    "        \n",
    "        self.X = tf.placeholder(tf.int32, [None, None])\n",
    "        self.Y = tf.placeholder(tf.int32, [None, None])\n",
    "        \n",
    "        self.X_seq_len = tf.count_nonzero(self.X, 1, dtype = tf.int32)\n",
    "        self.Y_seq_len = tf.count_nonzero(self.Y, 1, dtype = tf.int32)\n",
    "        batch_size = tf.shape(self.X)[0]\n",
    "        \n",
    "        embeddings = tf.Variable(tf.random_uniform([vocab_size, embedded_size], -1, 1))\n",
    "        \n",
    "        def forward(x, y, reuse = False):\n",
    "            batch_size = tf.shape(x)[0]\n",
    "            X_seq_len = tf.count_nonzero(x, 1, dtype = tf.int32)\n",
    "            Y_seq_len = tf.count_nonzero(y, 1, dtype = tf.int32)\n",
    "            with tf.variable_scope('model',reuse=reuse):\n",
    "                encoder_embedded = tf.nn.embedding_lookup(embeddings, x)\n",
    "                decoder_embedded = tf.nn.embedding_lookup(embeddings, y)\n",
    "                rnn_cells = tf.nn.rnn_cell.MultiRNNCell([cells() for _ in range(num_layers)])\n",
    "                last_output, last_state = tf.nn.dynamic_rnn(rnn_cells, encoder_embedded,\n",
    "                                                  sequence_length=X_seq_len,\n",
    "                                                  dtype = tf.float32)\n",
    "                \n",
    "            with tf.variable_scope(\"decoder\",reuse=reuse):\n",
    "                \n",
    "                attention_mechanism = tf.contrib.seq2seq.LuongAttention(num_units = size_layer, \n",
    "                                                                    memory = last_output)\n",
    "                rnn_cells = tf.contrib.seq2seq.AttentionWrapper(\n",
    "                    cell = tf.nn.rnn_cell.MultiRNNCell([cells() for _ in range(num_layers)]), \n",
    "                    attention_mechanism = attention_mechanism,\n",
    "                    attention_layer_size = size_layer)\n",
    "                \n",
    "                initial_state = rnn_cells.zero_state(batch_size, tf.float32).clone(cell_state=last_state)\n",
    "                outputs, _ = tf.nn.dynamic_rnn(rnn_cells, decoder_embedded, \n",
    "                                               sequence_length=Y_seq_len,\n",
    "                                               initial_state = initial_state,\n",
    "                                               dtype = tf.float32)\n",
    "                \n",
    "                return tf.layers.dense(outputs,vocab_size)\n",
    "            \n",
    "        main = tf.strided_slice(self.X, [0, 0], [batch_size, -1], [1, 1])\n",
    "        decoder_input = tf.concat([tf.fill([batch_size, 1], GO), main], 1)\n",
    "        self.training_logits = forward(self.X, decoder_input, reuse = False)\n",
    "        \n",
    "        self.training_logits = self.training_logits[:, :tf.reduce_max(self.Y_seq_len)]\n",
    "        self.training_logits = pad_second_dim(self.training_logits, tf.reduce_max(self.Y_seq_len))\n",
    "            \n",
    "        masks = tf.sequence_mask(self.Y_seq_len, tf.reduce_max(self.Y_seq_len), dtype=tf.float32)\n",
    "        self.cost = tf.contrib.seq2seq.sequence_loss(logits = self.training_logits,\n",
    "                                                     targets = self.Y,\n",
    "                                                     weights = masks)\n",
    "        self.optimizer = tf.train.AdamOptimizer(learning_rate = learning_rate).minimize(self.cost)\n",
    "        y_t = tf.argmax(self.training_logits,axis=2)\n",
    "        y_t = tf.cast(y_t, tf.int32)\n",
    "        self.prediction = tf.boolean_mask(y_t, masks)\n",
    "        mask_label = tf.boolean_mask(self.Y, masks)\n",
    "        correct_pred = tf.equal(self.prediction, mask_label)\n",
    "        correct_index = tf.cast(correct_pred, tf.float32)\n",
    "        self.accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))\n",
    "        \n",
    "        initial_ids = tf.fill([batch_size], GO)\n",
    "        def symbols_to_logits(ids):\n",
    "            x = tf.contrib.seq2seq.tile_batch(self.X, 1)\n",
    "            logits = forward(x, ids, reuse = True)\n",
    "            return logits[:, tf.shape(ids)[1]-1, :]\n",
    "        \n",
    "        final_ids, final_probs, _ = beam_search.beam_search(\n",
    "            symbols_to_logits,\n",
    "            initial_ids,\n",
    "            1,\n",
    "            tf.reduce_max(self.X_seq_len),\n",
    "            vocab_size,\n",
    "            0.0,\n",
    "            eos_id = EOS)\n",
    "        \n",
    "        self.fast_result = final_ids"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "size_layer = 512\n",
    "num_layers = 2\n",
    "embedded_size = 256\n",
    "learning_rate = 1e-3\n",
    "batch_size = 128\n",
    "epoch = 20"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/util/deprecation.py:507: calling count_nonzero (from tensorflow.python.ops.math_ops) with axis is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "reduction_indices is deprecated, use axis instead\n",
      "WARNING:tensorflow:From <ipython-input-7-19144da15f28>:11: BasicRNNCell.__init__ (from tensorflow.python.ops.rnn_cell_impl) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "This class is equivalent as tf.keras.layers.SimpleRNNCell, and will be replaced by that in Tensorflow 2.0.\n",
      "WARNING:tensorflow:From <ipython-input-7-19144da15f28>:29: MultiRNNCell.__init__ (from tensorflow.python.ops.rnn_cell_impl) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "This class is equivalent as tf.keras.layers.StackedRNNCells, and will be replaced by that in Tensorflow 2.0.\n",
      "WARNING:tensorflow:From <ipython-input-7-19144da15f28>:32: dynamic_rnn (from tensorflow.python.ops.rnn) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use `keras.layers.RNN(cell)`, which is equivalent to this API\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/ops/rnn_cell_impl.py:456: Layer.add_variable (from tensorflow.python.keras.engine.base_layer) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use `layer.add_weight` method instead.\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/ops/rnn_cell_impl.py:460: calling Zeros.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Call initializer instance with the dtype argument instead of passing it to the constructor\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/ops/rnn.py:244: where (from tensorflow.python.ops.array_ops) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Use tf.where in 2.0, which has the same broadcast rule as np.where\n",
      "WARNING:tensorflow:\n",
      "The TensorFlow contrib module will not be included in TensorFlow 2.0.\n",
      "For more information, please see:\n",
      "  * https://github.com/tensorflow/community/blob/master/rfcs/20180907-contrib-sunset.md\n",
      "  * https://github.com/tensorflow/addons\n",
      "  * https://github.com/tensorflow/io (for I/O related ops)\n",
      "If you depend on functionality not listed there, please file an issue.\n",
      "\n",
      "WARNING:tensorflow:From <ipython-input-7-19144da15f28>:49: dense (from tensorflow.python.layers.core) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Use keras.layers.Dense instead.\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/layers/core.py:187: Layer.apply (from tensorflow.python.keras.engine.base_layer) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use `layer.__call__` method instead.\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensor2tensor/utils/beam_search.py:745: to_float (from tensorflow.python.ops.math_ops) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Use `tf.cast` instead.\n"
     ]
    }
   ],
   "source": [
    "tf.reset_default_graph()\n",
    "sess = tf.InteractiveSession()\n",
    "model = Translator(size_layer, num_layers, embedded_size, learning_rate)\n",
    "sess.run(tf.global_variables_initializer())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "pad_sequences = tf.keras.preprocessing.sequence.pad_sequences"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[array([[[    1, 27596, 15058,  2924,  5882,  6397, 29587, 31461,  8350,\n",
       "          22072,  2044, 13758, 16254, 14291, 23526,  6488,  9524, 16930,\n",
       "          14951, 18239, 25162,   539, 25930, 27188, 29207, 20051, 15548,\n",
       "          16022,  4815,  4771, 19075, 14876, 13972,    12, 31170, 10489,\n",
       "           7344]],\n",
       " \n",
       "        [[    1,  7360, 11925, 20374, 17881, 25103,  3970,   242,  8167,\n",
       "          31870,  5012,   538,  6484, 17786, 11558, 19342, 25839, 29601,\n",
       "            799, 10085,  1200, 26253,  3995,  3398, 20489, 17403, 29792,\n",
       "          10201, 30725,  1811, 12774, 11033,   238, 26535, 15345,  8130,\n",
       "          22401]],\n",
       " \n",
       "        [[    1,  5921, 21908,  4617, 30062,  8172, 27859,   310, 26276,\n",
       "          29514,  9994, 18406,  5875, 10137, 22469, 27792,  1652, 19706,\n",
       "          25799, 29427, 23297, 31273, 17661, 10066, 26453,  1196,   955,\n",
       "          16781, 14645,  1653, 25320, 24628,  2384, 17661, 17152, 21436,\n",
       "          21658]],\n",
       " \n",
       "        [[    1, 21515,  3230, 31639, 30889, 13093, 18355,  6290,  3008,\n",
       "          30501,  3085, 30281,  9219,  8727, 25591,  4701, 24831, 10191,\n",
       "          14810, 28602, 11756, 19503,  2527,   727, 12500,  7722,  9977,\n",
       "           7367, 30485, 15424, 29197,  4344, 18668, 31812, 21254,  7313,\n",
       "           5195]],\n",
       " \n",
       "        [[    1, 14393, 20850, 29444, 22271, 21046, 22520, 30570, 21533,\n",
       "           2265, 13426, 22017, 16062,  7375,  8653, 21268, 26283, 31210,\n",
       "           2846,  7588, 20501, 10560, 11313, 16779, 21178, 31337, 31213,\n",
       "          14054,  1733,  9426,  9878, 30736, 11741, 18051,  1248,   637,\n",
       "          20110]],\n",
       " \n",
       "        [[    1, 29285,  9174, 23052, 23279, 23486,  6816,  2003, 19224,\n",
       "          17533,  5484,  2273, 15402, 13204,  2103,  5219, 16116,  1578,\n",
       "            823, 26916,  5357, 17096,  4147, 10053, 20938, 28860, 13580,\n",
       "          14735, 16614,   834, 14981, 10955, 24084, 17120, 13546, 22535,\n",
       "          29305]],\n",
       " \n",
       "        [[    1,  7172, 17728,   994, 18811, 28142,  8098, 21858, 21170,\n",
       "          17543, 31481, 18600, 11686, 26528, 23233,  2944, 23379, 27350,\n",
       "           5096, 13907, 14786,   647, 19748, 29882, 11277,  6127, 12400,\n",
       "           2273, 28941, 26191, 19230, 20852, 12040, 25189, 22582, 28042,\n",
       "          16348]],\n",
       " \n",
       "        [[    1, 17728, 29428, 31794, 29801, 11875, 16605, 16957, 10814,\n",
       "          30889,  2762, 10944,   755, 25085,  5285,  6217, 31843, 25201,\n",
       "          31726, 10971, 28107, 22255, 15704,  1373, 19618, 24813, 28372,\n",
       "           8780, 12478,  5278,   729, 29055, 19571, 31014, 14898, 14967,\n",
       "           7742]],\n",
       " \n",
       "        [[    1, 15577, 17527, 12210,  2537, 31746, 17234,  3044,  2724,\n",
       "          13463,  3368, 19271, 23381,  1799, 31160, 15737, 22752,   362,\n",
       "          12663, 29280,  5829, 10902, 21653,  1212, 20517, 24306,  2386,\n",
       "          28447, 29583, 23112,  1300,  2877,  1337, 11027, 19129, 19723,\n",
       "           6497]],\n",
       " \n",
       "        [[    1, 19222, 15829, 15808, 11394, 13204,  9152, 12789,  1349,\n",
       "          16745, 15300,  5622, 10390,  7480,  7904, 12515, 28611,  8853,\n",
       "          15266,  7155, 12664, 17535, 16674, 18758,  1149, 12656, 31539,\n",
       "          23785, 31813, 14694, 18188,  1390,  8870, 18717,   191, 15100,\n",
       "           2846]]], dtype=int32), 10.375248, 0.0]"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "batch_x = pad_sequences(train_X[:10], padding='post')\n",
    "batch_y = pad_sequences(train_Y[:10], padding='post')\n",
    "\n",
    "sess.run([model.fast_result, model.cost, model.accuracy], \n",
    "         feed_dict = {model.X: batch_x, model.Y: batch_y})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [06:47<00:00,  3.83it/s, accuracy=0.0875, cost=7.18]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:05<00:00,  7.33it/s, accuracy=0.0968, cost=7.07]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 1, training avg loss 7.371482, training avg acc 0.090744\n",
      "epoch 1, testing avg loss 7.108765, testing avg acc 0.101567\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [06:51<00:00,  3.80it/s, accuracy=0.095, cost=6.92] \n",
      "minibatch loop: 100%|██████████| 40/40 [00:05<00:00,  7.50it/s, accuracy=0.086, cost=7.15] \n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 2, training avg loss 7.016725, training avg acc 0.100828\n",
      "epoch 2, testing avg loss 7.155285, testing avg acc 0.101836\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [06:51<00:00,  3.80it/s, accuracy=0.0651, cost=8.19]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:05<00:00,  7.48it/s, accuracy=0.086, cost=7.69] \n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 3, training avg loss 7.369245, training avg acc 0.100070\n",
      "epoch 3, testing avg loss 8.173422, testing avg acc 0.070131\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [06:50<00:00,  3.80it/s, accuracy=0.0271, cost=21.5]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:05<00:00,  7.50it/s, accuracy=0.0215, cost=19.5]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 4, training avg loss 17.587063, training avg acc 0.046417\n",
      "epoch 4, testing avg loss 20.180908, testing avg acc 0.032263\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [06:51<00:00,  3.80it/s, accuracy=0.0387, cost=13]  \n",
      "minibatch loop: 100%|██████████| 40/40 [00:05<00:00,  7.42it/s, accuracy=0.043, cost=11.7] \n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 5, training avg loss 17.472757, training avg acc 0.040391\n",
      "epoch 5, testing avg loss 12.261106, testing avg acc 0.046303\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [06:51<00:00,  3.80it/s, accuracy=0.0482, cost=10.1]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:05<00:00,  7.46it/s, accuracy=0.043, cost=9.59] \n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 6, training avg loss 11.139873, training avg acc 0.050595\n",
      "epoch 6, testing avg loss 9.842271, testing avg acc 0.053645\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [06:51<00:00,  3.80it/s, accuracy=0.0611, cost=9.15]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:05<00:00,  7.49it/s, accuracy=0.0591, cost=8.74]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 7, training avg loss 9.391773, training avg acc 0.063232\n",
      "epoch 7, testing avg loss 8.921453, testing avg acc 0.068466\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [06:51<00:00,  3.80it/s, accuracy=0.0577, cost=8.55]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:05<00:00,  7.49it/s, accuracy=0.0591, cost=8.24]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 8, training avg loss 8.623529, training avg acc 0.069070\n",
      "epoch 8, testing avg loss 8.380180, testing avg acc 0.071039\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [06:51<00:00,  3.80it/s, accuracy=0.0577, cost=8.04]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:05<00:00,  7.40it/s, accuracy=0.0591, cost=7.9] \n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 9, training avg loss 8.164516, training avg acc 0.074765\n",
      "epoch 9, testing avg loss 7.964720, testing avg acc 0.073864\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [06:50<00:00,  3.80it/s, accuracy=0.0305, cost=69.8]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:05<00:00,  7.48it/s, accuracy=0.0161, cost=55.8]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 10, training avg loss 37.586876, training avg acc 0.061134\n",
      "epoch 10, testing avg loss 63.202187, testing avg acc 0.029087\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [06:51<00:00,  3.80it/s, accuracy=0.0353, cost=45]  \n",
      "minibatch loop: 100%|██████████| 40/40 [00:05<00:00,  7.51it/s, accuracy=0.0161, cost=34.5]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 11, training avg loss 46.036999, training avg acc 0.035663\n",
      "epoch 11, testing avg loss 38.008446, testing avg acc 0.029088\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [06:50<00:00,  3.80it/s, accuracy=0.0258, cost=66.3]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:05<00:00,  7.45it/s, accuracy=0.0215, cost=64.9]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 12, training avg loss 36.194557, training avg acc 0.036156\n",
      "epoch 12, testing avg loss 65.089195, testing avg acc 0.031477\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [06:50<00:00,  3.81it/s, accuracy=0.0231, cost=40.8]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:05<00:00,  7.51it/s, accuracy=0.0161, cost=38.4]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 13, training avg loss 48.986206, training avg acc 0.033942\n",
      "epoch 13, testing avg loss 39.820057, testing avg acc 0.031298\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [06:51<00:00,  3.80it/s, accuracy=0.0455, cost=28.8]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:05<00:00,  7.55it/s, accuracy=0.0269, cost=24.9]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 14, training avg loss 35.727451, training avg acc 0.037294\n",
      "epoch 14, testing avg loss 28.603968, testing avg acc 0.037545\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [06:50<00:00,  3.80it/s, accuracy=0.0265, cost=31]  \n",
      "minibatch loop: 100%|██████████| 40/40 [00:05<00:00,  7.53it/s, accuracy=0.0215, cost=26.1]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 15, training avg loss 30.052616, training avg acc 0.039463\n",
      "epoch 15, testing avg loss 28.910229, testing avg acc 0.031194\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [06:50<00:00,  3.81it/s, accuracy=0.0502, cost=20.6]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:05<00:00,  7.52it/s, accuracy=0.0484, cost=17.5]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 16, training avg loss 24.234406, training avg acc 0.041178\n",
      "epoch 16, testing avg loss 20.610571, testing avg acc 0.050825\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [06:51<00:00,  3.80it/s, accuracy=0.0387, cost=12.5]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:05<00:00,  7.44it/s, accuracy=0.0376, cost=11.7]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 17, training avg loss 16.007160, training avg acc 0.049149\n",
      "epoch 17, testing avg loss 11.425888, testing avg acc 0.037923\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [06:51<00:00,  3.80it/s, accuracy=0.055, cost=8.95] \n",
      "minibatch loop: 100%|██████████| 40/40 [00:05<00:00,  7.38it/s, accuracy=0.0591, cost=9.49]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 18, training avg loss 10.449832, training avg acc 0.055571\n",
      "epoch 18, testing avg loss 8.945489, testing avg acc 0.068504\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [06:50<00:00,  3.81it/s, accuracy=0.0556, cost=8.11]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:05<00:00,  7.42it/s, accuracy=0.0484, cost=8.63]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 19, training avg loss 8.324727, training avg acc 0.065994\n",
      "epoch 19, testing avg loss 8.156435, testing avg acc 0.067655\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [06:51<00:00,  3.80it/s, accuracy=0.059, cost=7.82] \n",
      "minibatch loop: 100%|██████████| 40/40 [00:05<00:00,  7.48it/s, accuracy=0.0538, cost=8.13]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 20, training avg loss 7.924156, training avg acc 0.070114\n",
      "epoch 20, testing avg loss 7.826285, testing avg acc 0.067840\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "\n"
     ]
    }
   ],
   "source": [
    "import tqdm\n",
    "\n",
    "for e in range(epoch):\n",
    "    pbar = tqdm.tqdm(\n",
    "        range(0, len(train_X), batch_size), desc = 'minibatch loop')\n",
    "    train_loss, train_acc, test_loss, test_acc = [], [], [], []\n",
    "    for i in pbar:\n",
    "        index = min(i + batch_size, len(train_X))\n",
    "        batch_x = pad_sequences(train_X[i : index], padding='post')\n",
    "        batch_y = pad_sequences(train_Y[i : index], padding='post')\n",
    "        feed = {model.X: batch_x,\n",
    "                model.Y: batch_y}\n",
    "        accuracy, loss, _ = sess.run([model.accuracy,model.cost,model.optimizer],\n",
    "                                    feed_dict = feed)\n",
    "        train_loss.append(loss)\n",
    "        train_acc.append(accuracy)\n",
    "        pbar.set_postfix(cost = loss, accuracy = accuracy)\n",
    "    \n",
    "    \n",
    "    pbar = tqdm.tqdm(\n",
    "        range(0, len(test_X), batch_size), desc = 'minibatch loop')\n",
    "    for i in pbar:\n",
    "        index = min(i + batch_size, len(test_X))\n",
    "        batch_x = pad_sequences(test_X[i : index], padding='post')\n",
    "        batch_y = pad_sequences(test_Y[i : index], padding='post')\n",
    "        feed = {model.X: batch_x,\n",
    "                model.Y: batch_y,}\n",
    "        accuracy, loss = sess.run([model.accuracy,model.cost],\n",
    "                                    feed_dict = feed)\n",
    "\n",
    "        test_loss.append(loss)\n",
    "        test_acc.append(accuracy)\n",
    "        pbar.set_postfix(cost = loss, accuracy = accuracy)\n",
    "    \n",
    "    print('epoch %d, training avg loss %f, training avg acc %f'%(e+1,\n",
    "                                                                 np.mean(train_loss),np.mean(train_acc)))\n",
    "    print('epoch %d, testing avg loss %f, testing avg acc %f'%(e+1,\n",
    "                                                              np.mean(test_loss),np.mean(test_acc)))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [],
   "source": [
    "from tensor2tensor.utils import bleu_hook"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 40/40 [02:14<00:00,  3.35s/it]\n"
     ]
    }
   ],
   "source": [
    "results = []\n",
    "for i in tqdm.tqdm(range(0, len(test_X), batch_size)):\n",
    "    index = min(i + batch_size, len(test_X))\n",
    "    batch_x = pad_sequences(test_X[i : index], padding='post')\n",
    "    feed = {model.X: batch_x}\n",
    "    p = sess.run(model.fast_result,feed_dict = feed)[:,0,:]\n",
    "    result = []\n",
    "    for row in p:\n",
    "        result.append([i for i in row if i > 3])\n",
    "    results.extend(result)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [],
   "source": [
    "rights = []\n",
    "for r in test_Y:\n",
    "    rights.append([i for i in r if i > 3])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "8.97118e-05"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "bleu_hook.compute_bleu(reference_corpus = rights,\n",
    "                       translation_corpus = results)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
